﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using DunSilverlight.Comm;
using DunSilverlight.OrganziationService;
using Telerik.Windows.Controls;
using DunSilverlight.UserService;
using DunSilverlight.ViewModel;

namespace DunSilverlight.Views
{
    public partial class UserPanel : Page
    {
        RoleService.RoleServiceClient roleSer = new RoleService.RoleServiceClient();
        OrganizationServiceClient oser = new OrganizationServiceClient();
        UserServiceClient uservice = new UserServiceClient();


        public UserPanel()
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Organization_Manage))
            {
                if (AppGlobal.CurrentUser != null)
                    Tools.ShowMessage("该用户没有权限查看 ", "", false);
                return;
            }
            InitializeComponent();
            
            this.Loaded += new RoutedEventHandler(UserPanel_Loaded);

            roleSer.GetRolesCompleted += new EventHandler<RoleService.GetRolesCompletedEventArgs>(roleSer_GetRolesCompleted);
            
            oser.GetUsersCompleted += new EventHandler<DunSilverlight.OrganziationService.GetUsersCompletedEventArgs>(oser_GetUsersCompleted);
            oser.GetUserOrgCompleted += new EventHandler<GetUserOrgCompletedEventArgs>(oser_GetUserOrgCompleted);
            oser.DeleteByIdCompleted += new EventHandler<OrganziationService.DeleteByIdCompletedEventArgs>(oser_DeleteByIdCompleted);
            uservice.SaveOrUpdateCompleted += new EventHandler<UserService.SaveOrUpdateCompletedEventArgs>(userive_SaveOrUpdateCompleted);
            uservice.DeleteByIdCompleted += new EventHandler<UserService.DeleteByIdCompletedEventArgs>(userive_DeleteByIdCompleted);
        }

       
        void UserPanel_Loaded(object sender, RoutedEventArgs e)
        {
            //生成该用户具有权限的组织机构树
            
            oser.GetUserOrgAsync(AppGlobal.CurrentUser.Id);

            roleSer.GetRolesAsync();
           
        }

        void oser_GetUserOrgCompleted(object sender, GetUserOrgCompletedEventArgs e)
        {
            RadTreeView1.Items.Clear();
            cboxOrg.Items.Clear();
            var root = JsonSerializerHelper.JsonToEntity<DunLibrary.Organization.Organization>(e.Result);
            if (root != null)
            {
                var item = new RadTreeViewItem
                {
                    Header = root.Name,
                    Tag = root,
                    IsExpanded = true,
                    DefaultImageSrc = "/Images/blue-folder-horizontal-open.png"
                };
                RadTreeView1.Items.Add(item);
                cboxOrg.Items.Add(root);
                bindChildren(item, root);
            }
        }


        void roleSer_GetRolesCompleted(object sender, RoleService.GetRolesCompletedEventArgs e)
        {
            int total = 0;
            IList<DunLibrary.User.Role> cases = JsonSerializerHelper.JsonToEntities<DunLibrary.User.Role>(e.Result, out total);
            cboxRole.ItemsSource = cases;
        }

        

        private void bindChildren(RadTreeViewItem parent, DunLibrary.Organization.Organization root)
        {
            if( root.Childs!=null)
            {
                foreach (var child in root.Childs)
                {
                    var item = new RadTreeViewItem { Header = child.Name, Tag = child, IsExpanded=true,
                                                     DefaultImageSrc = "/Images/document.png"
                    };
                    parent.Items.Add(item);
                    cboxOrg.Items.Add(child);
                    bindChildren(item, child);
                }
            }
        }

        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

        }

        private void rDataPager1_PageIndexChanged(object sender, Telerik.Windows.Controls.PageIndexChangedEventArgs e)
        {

        }

        /// <summary>
        /// 组织结构下的user tree选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                DunLibrary.User.User entity = e.AddedItems[0] as DunLibrary.User.User;
                del1.IsEnabled = entity.Name != "admin";
                UserModel obj = UserModel.Create(entity);
                userInfo.DataContext = obj;
                tbPadConfirm.Password = tbPad.Password;
                //不能改变自己的角色，如管理员将自己的角色改为业务员
                if (AppGlobal.CurrentUser.Id == entity.Id)
                {
                    cboxRole.IsEnabled = false;
                }
                else
                {
                    cboxRole.IsEnabled = true;
                }
            }
        }

        /// <summary>
        /// 新建用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Add1_Click(object sender, RoutedEventArgs e)
        {
            UserForm user = new UserForm();
            Tools.OpenWindow("新建用户", user, null, new Action(() =>
            {
                if (RadTreeView1.SelectedItem != null)
                {
                    var org = (RadTreeView1.SelectedItem as RadTreeViewItem).Tag as DunLibrary.Organization.Organization;


                    oser.GetUsersAsync(org.Id);
                }
            }));
        }

        private void RadTreeView1_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var org = (e.AddedItems[0] as RadTreeViewItem).Tag as DunLibrary.Organization.Organization;


                oser.GetUsersAsync(org.Id);
            }
           
        }

        void oser_GetUsersCompleted(object sender, DunSilverlight.OrganziationService.GetUsersCompletedEventArgs e)
        {
            int totalCount;
            var list = JsonSerializerHelper.JsonToEntities<DunLibrary.User.User>(e.Result,out totalCount);
            //List<UserModel> modelList = new List<UserModel>();
            //foreach (var item in list)
            //{
            //    modelList.Add(UserModel.Create(item));
            //}
            //UserGrid.ItemsSource = modelList;
            UserGrid.ItemsSource = list;
            if (UserGrid.Items.Count > 0)
            {
                //判断是否有用户参数（修改user的id）
                if (e.UserState == null)
                {
                    UserGrid.SelectedIndex = 0;
                }
                else
                {
                    var updatedItem = list.SingleOrDefault(c=>c.Id == int.Parse(e.UserState.ToString()));
                    if (updatedItem != null)
                        UserGrid.SelectedItem = updatedItem;
                    else
                        UserGrid.SelectedIndex = 0;
                }
                Save.IsEnabled = true;
            }
            else
            {
                userInfo.DataContext = null;
                tbPadConfirm.Password = tbPad.Password;
                Save.IsEnabled = false;
            }
        }

        /// <summary>
        /// 保存用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            if (tbPad.Password != tbPadConfirm.Password)
            {
                Tools.ShowMessage("密码不一致，请重新输入", "", false);
                tbPad.Password = "";
                tbPadConfirm.Password = "";
                tbPad.Focus();
                return;
            }
            var obj = userInfo.DataContext as UserModel;
            if (obj.Validation())
            {
                var entity = obj.ToEntity();
                uservice.SaveOrUpdateAsync(JsonSerializerHelper.EntityToJson(entity),entity.Id);
            }
            else
            {
                Tools.ShowMessage("输入格式不正确", "", false);
            }

        }

        void userive_SaveOrUpdateCompleted(object sender, UserService.SaveOrUpdateCompletedEventArgs e)
        {
            var user = JsonSerializerHelper.JsonToEntity<DunLibrary.User.User>(e.Result);
            if (user != null && user.Id == AppGlobal.CurrentUser.Id)
            {
                AppGlobal.CurrentUser = user;
            }

            if (RadTreeView1.SelectedItem!=null)
            {
                var org = (RadTreeView1.SelectedItem as RadTreeViewItem).Tag as DunLibrary.Organization.Organization;


                oser.GetUsersAsync(org.Id,e.UserState);
            }
        }

        /// <summary>
        /// 刷新组织机构树
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            oser.GetUserOrgAsync(AppGlobal.CurrentUser.Id);
        }

        /// <summary>
        /// 新建组织机构
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Add_Click(object sender, RoutedEventArgs e)
        {
            OrgForm form = new OrgForm();
            Tools.OpenWindow("新建组织机构", form, null,  new Action(() =>  oser.GetUserOrgAsync(AppGlobal.CurrentUser.Id)));
        }
        /// <summary>
        /// 删除组织机构
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void del_Click(object sender, RoutedEventArgs e)
        {
            if (RadTreeView1.Items.Count > 0 && RadTreeView1.SelectedItem != null)
            {
                DunLibrary.Organization.Organization org = (RadTreeView1.SelectedItem as RadTreeViewItem).Tag as DunLibrary.Organization.Organization;
                if (org.Childs.Count > 0)
                {
                    Tools.ShowMessage("该节点含有子节点，不能被删除", "如果要删除该节点，请先删除所有子节点", false);
                    return;
                }

                if (UserGrid.Items.Count > 0)
                {
                    Tools.ShowMessage("该节点含有用户，不能被删除", "如果要删除该节点，请先删除所有用户", false);
                    return;
                }
                EventHandler<WindowClosedEventArgs> callback = new EventHandler<WindowClosedEventArgs>(
                    (o,args)=> {if(args.DialogResult == true) oser.DeleteByIdAsync(org.Id); });
                Tools.OpenConfirm("确定要删除吗?", callback);
            }
        }

        void oser_DeleteByIdCompleted(object sender, OrganziationService.DeleteByIdCompletedEventArgs e)
        {
            oser.GetUserOrgAsync(AppGlobal.CurrentUser.Id);
        }

        /// <summary>
        /// 刷新人员列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Refresh1_Click(object sender, RoutedEventArgs e)
        {
            if (RadTreeView1.Items.Count > 0 && RadTreeView1.SelectedItem != null)
            {
                var org = (RadTreeView1.SelectedItem as RadTreeViewItem).Tag as DunLibrary.Organization.Organization;

                oser.GetUsersAsync(org.Id);
            }
        }

        /// <summary>
        /// 删除人员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void del1_Click(object sender, RoutedEventArgs e)
        {
            if (UserGrid.Items.Count > 0 && UserGrid.SelectedItem != null)
            {
                DunLibrary.User.User user = (UserGrid.SelectedItem as DunLibrary.User.User);

                if (user.Id == AppGlobal.CurrentUser.Id)
                {
                    Tools.ShowMessage("不能删除自己！", "", false);
                    return;
                }
               
                EventHandler<WindowClosedEventArgs> callback = new EventHandler<WindowClosedEventArgs>(
                    (o, args) => { if (args.DialogResult == true) uservice.DeleteByIdAsync(user.Id); });
                Tools.OpenConfirm("确定要删除吗?", callback);
            }
        }

        void userive_DeleteByIdCompleted(object sender, UserService.DeleteByIdCompletedEventArgs e)
        {
            if (RadTreeView1.Items.Count > 0 && RadTreeView1.SelectedItem != null)
            {
                var org = (RadTreeView1.SelectedItem as RadTreeViewItem).Tag as DunLibrary.Organization.Organization;
                oser.GetUsersAsync(org.Id);
            }
        }

       
    }
}
